package com.myjuniu.scanner;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;

import com.myjuniu.factory.sunmi.sh.MainActivity;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author Juniu
 */
public class Scanner extends CordovaPlugin {
    private Vibrator mVibrator;
    private MediaPlayer mMediaPlayer;
    private CallbackContext mCallbackContext;
    private static final String SET_SCAN_CALLBACK_ACTION = "setScanCallback";

    @Override
    protected void pluginInitialize() {
        scannerInit();
        mediaPlayerInit();
        vibratorInit();
    }

    private void scannerInit() {
        Handler scanHandler = new ScanHandler();
        MainActivity mainActivity = (MainActivity) cordova.getActivity();
        mainActivity.SetHandler(scanHandler);
    }

    private void mediaPlayerInit() {
        mMediaPlayer = new MediaPlayer();
        int mediaIdentifier = cordova.getActivity().getResources()
                .getIdentifier("scan", "raw", cordova.getActivity().getPackageName());
        mMediaPlayer = MediaPlayer.create(cordova.getActivity(), mediaIdentifier);
        mMediaPlayer.setLooping(false);
    }

    private void vibratorInit() {
        mVibrator = (Vibrator) cordova.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
    }

    @Override
    public void onDestroy() {
        mMediaPlayer.stop();
        mMediaPlayer.release();
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (SET_SCAN_CALLBACK_ACTION.equals(action)) {
            mCallbackContext = callbackContext;
            return true;
        }
        return false;
    }

    class ScanHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MainActivity.BARCODE_READ:
                    Log.d("barcode", msg.obj.toString());
                    JSONObject parameter = new JSONObject();
                    try {
                        parameter.put("barcode", msg.obj.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    PluginResult result = new PluginResult(PluginResult.Status.OK, parameter);
                    result.setKeepCallback(true);
                    mCallbackContext.sendPluginResult(result);
                    mMediaPlayer.start();
                    if (mVibrator.hasVibrator()) {
                        mVibrator.vibrate(100);
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
